<template>
  <el-drawer
    :title="!dataForm.id ? '新增' : '修改'"
    :visible="visible"
    size="70vw"
    @close="closeDialog"
    append-to-body
  >
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      label-width="120px"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="权益包名称" prop="equityName">
            <el-input
              v-model="dataForm.equityName"
              placeholder="请输入权益包名称"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="权益包副标题" prop="equityShortName">
            <el-input
              v-model="dataForm.equityShortName"
              placeholder="请输入权益包名称"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="时间范围" prop="expirationDateRange">
            <el-tooltip class="item" effect="dark" content="用于显示在权益包详情，计算剩余天数" placement="bottom">
              <el-date-picker
                v-model="dataForm.expirationDateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                value-format="yyyy-MM-dd"
                end-placeholder="结束日期">
              </el-date-picker>
            </el-tooltip>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          
        </el-col>
      </el-row>

      <el-row v-if="goodsServerList.length > 0">
        <el-form-item label="保障服务" prop="goodsServerIds">
          <el-checkbox-group v-model="dataForm.goodsServerIds">
            <el-checkbox :label="item.id" v-for="(item, index) in goodsServerList" :key="index">{{item.serverName}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-row>
      
      <el-form-item label="权益包轮播图" prop="bannerImages">
        <ImagesUpload v-model="dataForm.bannerImages"></ImagesUpload>
      </el-form-item>
      <el-form-item label="权益包详情图" prop="detailImages">
        <ImagesUpload v-model="dataForm.detailImages"></ImagesUpload>
      </el-form-item>

      <el-form-item label="优惠券列表" prop="couponIds">
        <div class="avue-crud">
          <el-table ref="goodsTable" :data="couponList" border v-loading="dataListLoading" :row-key="getRowKey" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" :reserve-selection="true"> </el-table-column>
            <el-table-column
              type="index"
              header-align="center"
              align="center"
              label="编号">
            </el-table-column>
            <el-table-column
              prop="couponName"
              header-align="center"
              align="center"
              label="优惠券名称">
            </el-table-column>
            <el-table-column
              prop="couponType"
              header-align="center"
              align="center"
              label="类型">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.couponType === '1'">代金券</el-tag>
                <el-tag v-else>折扣券</el-tag>
              </template>
            </el-table-column>
            <el-table-column
              prop="orderPrice"
              header-align="center"
              align="center"
              label="订单金额"
              :formatter="formatMoney">
            </el-table-column>
            <el-table-column
              prop="orderPrice"
              header-align="center"
              align="center"
              label="优惠减免">
              <template slot-scope="scope">
                <template v-if="scope.row.couponType == '1'">
                  <span>-</span>
                  <span style="margin-left: 5px">{{scope.row.deductionPrice | formatMoneyToYuanFilter}}</span>
                </template>
                <template v-else-if="scope.row.couponType == '2'">
                  <span >{{scope.row.discountRate | formatRateFilter}}</span>
                  <span style="margin-left: 2px">折</span>
                </template>
                <template v-else>
                  <span>未知</span>
                </template>
              </template>
            </el-table-column>
            <el-table-column
              prop="createTime"
              header-align="center"
              align="center"
              label="创建时间"
            >
            </el-table-column>
          </el-table>
        </div>
      </el-form-item>
      <el-row>
        <el-col :span="12">
          <el-form-item label="积分策略" prop="pointPolicyId">
            <el-tooltip class="item" effect="dark" content="当设置了积分策略后，用户购买权益包后会立即获得积分, 这里只能设置固定的积分策略" placement="bottom">
              <el-select
                v-model="dataForm.pointPolicyId"
                filterable
                placeholder="请选择推广渠道"
                clearable
                style="width:100%">
                <el-option
                  v-for="dict in pointPolicyList"
                  :key="dict.id"
                  :label="dict.policyName"
                  :value="dict.id">
                </el-option>
              </el-select>
            </el-tooltip>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="销售价格" prop="sellPrice">
            <el-input
              v-model="dataForm.sellPrice"
              placeholder="请输入销售价格"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row>
        <el-col :span="12">
          <el-form-item label="减免金额" prop="subPrice">
            <el-input v-model.number="dataForm.subPrice" placeholder="请输入减免金额"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="上架状态:" prop="status">
            <el-radio-group v-model="dataForm.status">
              <el-radio label="1" border>上架</el-radio>
              <el-radio label="0" border>下架</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row>
        <el-col :span="12">
          <el-form-item label="虚拟销量:" prop="virtualSales">
            <el-input v-model="dataForm.virtualSales"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="推广渠道" prop="channelCode">
            <el-select
              v-model="dataForm.channelCode"
              filterable
              placeholder="请选择推广渠道"
              clearable
              style="width:100%"
            >
              <el-option
                v-for="dict in channelList"
                :key="dict.channelCode"
                :label="dict.channelName"
                :value="dict.channelCode">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-form-item label="排序:" prop="sort">
            <el-input-number
              v-model="dataForm.sort"
              controls-position="right"
              :min="1"
            />
          </el-form-item>
      </el-row>

      <el-form-item label="权益包规格说明" prop="remark" style="padding-bottom: 100px">
        <quill-editor
            class="editor"
            v-model="dataForm.remark"
            ref="myQuillEditor"
            :options="editorOption">
        </quill-editor>
      </el-form-item>
    </el-form>
    <div class="dialog__footer">
      <el-button @click="closeDialog">取 消</el-button>
      <el-button type="primary" @click="dataFormSubmit">确 定</el-button>
    </div>
  </el-drawer>
</template>

<script>
import { getObj, addObj, putObj } from "@/api/shop_operate/equity";
import ImageUploadSingle from '@/components/imageUploadSingle';
import ImagesUpload from "@/components/imagesUpload";
import { fetchList} from "@/api/shop_operate/coupon";
import {CouponCateEnum, PointPolicyTypeEnum} from '@/const/const';
import {getPromotionChannelList} from '@/api/shop_user/promotion_channel'
import {getPointPolicyList} from '@/api/shop_operate/point_policy';
import { quillEditor } from 'vue-quill-editor'
import {getGoodsServerList} from '@/api/shop_config/server';

export default {
  props:{
    visible: {
      type: Boolean,
      default: false
    },
  },
  data() {
    return {
      PointPolicyTypeEnum,
      CouponCateEnum,
      dataListLoading:false,
      canSubmit: false,
      dataForm: {
        bannerImages:[],
        detailImages:[],
        status:'1',
        sort:1,
        goodsServerIds:[],
        // 时间范围
        expirationDateRange:[],
      },
      dataRule: {
        equityName: [
          { required: true, message: "权益包名称不能为空", trigger: "blur" },
        ],
        equityShortName:[
          { required: true, message: "权益包副标题不能为空", trigger: "blur" },
        ],
        channelCode:[
          { required: true, message: "推广渠道不能为空", trigger: "blur" },
        ],
        bannerImages: [
          { required: true, message: "权益包轮播图不能为空", trigger: "blur" },
        ],
        detailImages: [
          { required: true, message: "权益包详情图不能为空", trigger: "blur" },
        ],
        status: [
          { required: true, message: "上架状态不能为空", trigger: "blur" },
        ],
        sort: [
          { required: true, message: "排序不能为空", trigger: "blur" },
        ],
        sellPrice:[
          { required: true, message: "销售价格不能为空", trigger: "blur" },
        ],
        virtualSales:[
          { required: true, message: "虚拟销量不能为空", trigger: "blur" },
        ],
        expirationDateRange:[
          { required: true, message: "时间范围不能为空", trigger: "blur" },
        ],
        subPrice:[
          { required: true, message: "减免金额不能为空", trigger: "blur" },
        ],
      },
      // 优惠券列表
      couponList:[],
      // 渠道列表
      channelList:[],
      // 积分策略列表
      pointPolicyList:[],
      // 选中的优惠券
      multipleSelection:[],
      // 保障服务
      goodsServerList:[],

      // 富文本编辑器配置
      editorOption: {
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线
            ['blockquote', 'code-block'], // 引用  代码块
            [{ header: 1 }, { header: 2 }], // 1、2 级标题
            [{ list: 'ordered' }, { list: 'bullet' }], // 有序、无序列表
            [{ script: 'sub' }, { script: 'super' }], // 上标/下标
            [{ indent: '-1' }, { indent: '+1' }], // 缩进
            [{ direction: 'rtl' }], // 文本方向
            [{ size: ['small', false, 'large', 'huge'] }], // 字体大小
            [{ header: [1, 2, 3, 4, 5, 6] }], // 标题
            [{ color: [] }, { background: [] }], // 字体颜色、字体背景颜色
            // [{ font: ['songti'] }], // 字体种类
            [{ align: [] }], // 对齐方式
            ['clean'], // 清除文本格式
            ['image', 'video'] // 链接、图片、视频
          ]
        },
        placeholder: '请输入正文'
      },

    };
  },
  components: {
    ImageUploadSingle,
    ImagesUpload,
    quillEditor
  },
  watch:{
  },
  methods: {
    getRowKey(row) {
      return row.id 
    },

    init(id) {
      // 获取保障服务
      this.getGoodsServerList()
      // 获取可用渠道
      this.getPromotionChannelList()
      // 获取购买类型的优惠券列表
      this.getCouponList()
      // 获取积分策略
      this.getPointPolicyList()

      if(id){
        // 获取详情
        getObj(id).then((response) => {
          let data = response.data.data;
          data.bannerImages = data.bannerImages ? JSON.parse(data.bannerImages) : []
          data.detailImages = data.detailImages ? JSON.parse(data.detailImages) : []
          data.goodsServerIds = data.goodsServerIds ? data.goodsServerIds.split(',') : []
          // 销售价格转元
          data.sellPrice = this.formatMoneyToYuan(data.sellPrice)
          // 减免金额转元
          data.subPrice = this.formatMoneyToYuan(data.subPrice)

          // 格式化时间区间
          if(data.startDate && data.endDate){
            this.$set(data, 'expirationDateRange', [])
            data.expirationDateRange.push(this.dayjs(data.startDate).format('YYYY-MM-DD'))
            data.expirationDateRange.push(this.dayjs(data.endDate).format('YYYY-MM-DD'))
          }

          if(data.equityCoupons){
            // 获取选择的优惠券
            data.equityCoupons.forEach(equityCoupon=>{
              let coupons = this.couponList.filter(p=>p.id == equityCoupon.couponId)
              if(coupons.length > 0){
                this.multipleSelection.push(coupons[0])
              }
            })
            // 回显优惠券
            this.multipleSelection.forEach(item=>{
              this.$refs.goodsTable.toggleRowSelection(item)
            })
          }
          this.dataForm = data
          this.canSubmit = true;
        });
      } else {
        this.canSubmit = true;
      }
    },

    /**
    * 获取勾选项目
    */
    handleSelectionChange(val) {
      this.multipleSelection = val;
      console.log(this.multipleSelection)
    },

    /**
     * 获取渠道
     */
    getPromotionChannelList(){
      getPromotionChannelList().then(res=>{
        this.channelList = res.data.data
      })
    },

     /**
     * 获取保障服务
     */
     getGoodsServerList(){
      getGoodsServerList().then(res=>{
        this.goodsServerList = res.data.data
      })
    },

    /**
     * 获取购买类型的优惠券列表
     */
    getCouponList(){
      this.dataListLoading = true;
      fetchList(
        Object.assign({
          current: 1,
          size: 20,
          couponCate: CouponCateEnum.pay,
          status: '1' // 已上架的优惠券
        })
      ).then((response) => {
        this.dataListLoading = false;
        this.couponList = response.data.data.records
      });
    },

    /**
     * 获取固定积分策略
     */
    getPointPolicyList(){
      getPointPolicyList({
        policyType: PointPolicyTypeEnum.flxPoint
      }).then(res=>{
        this.pointPolicyList = res.data.data
      })
    },

    // 表单提交
    dataFormSubmit() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          this.canSubmit = false;
          let requestData = JSON.parse(JSON.stringify(this.dataForm))
          requestData.bannerImages = requestData.bannerImages.map(p=>p.materialId).join()
          requestData.detailImages = requestData.detailImages.map(p=>p.materialId).join()
          requestData.sellPrice = this.formatMoneyToFen(requestData.sellPrice)
          requestData.equityCoupons = []
          if(this.multipleSelection.length > 0){
            this.multipleSelection.forEach(item=>{
              requestData.equityCoupons.push({
                couponId: item.id
              })
            })
          }
          // 保障服务Ids
          if(requestData.goodsServerIds.length > 0){
            requestData.goodsServerIds = requestData.goodsServerIds.join()
          } else {
            requestData.goodsServerIds = ''
          }

          // 时间区间
          if(requestData.expirationDateRange && requestData.expirationDateRange.length > 0){
            requestData.startDate = requestData.expirationDateRange[0] + " 00:00:00"
            requestData.endDate = requestData.expirationDateRange[1] + " 23:59:59"
          }
          // 减免金额
          requestData.subPrice = this.formatMoneyToFen(requestData.subPrice)
          
          if (requestData.id) {
            putObj(requestData)
              .then((data) => {
                this.$notify.success("修改成功");
                this.$emit("refreshDataList");
                this.closeDialog()
              })
              .catch(() => {
                this.canSubmit = true;
              });
          } else {
            addObj(requestData)
              .then((data) => {
                this.$notify.success("添加成功");
                this.$emit("refreshDataList");
                this.closeDialog()
              })
              .catch(() => {
                this.canSubmit = true;
              });
          }
        }
      });
    },
    //重置表单
    closeDialog() {
      this.$emit('update:visible', false)
    },
  },
};
</script>


<style scoped>
.dialog__footer {
  display: block;
  padding: 10px 16px;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  border-top: 1px solid #f0f0f0;
  width: 100%;
  position: absolute;
  left: 0;
  bottom: 0;
  background-color: #fff;
  text-align: right;
}
</style>
